import json
from django.utils import timezone

from django import http
from django.db import transaction
from django.shortcuts import render

# Create your views here.
from decimal import Decimal

from django.views import View
from django_redis import get_redis_connection

from goods.models import SKU
from meiduo_mall.utils.view import LoginRequiredMixin
from orders.models import OrderInfo, OrderGoods
from users.models import Address


class OrderSettlementView(LoginRequiredMixin, View):
    """结算订单"""

    def get(self, request):
        """提供订单结算页面"""
        # 获取登录用户
        user = request.user
        # 查询地址信息
        try:
            addresses = Address.objects.filter(user=request.user,
                                               is_deleted=False)
        except Exception as e:
            # 如果地址为空，渲染模板时会判断，并跳转到地址编辑页面
            addresses = None

        # 遍历所有地址
        list = []
        for address in addresses:
            list.append({
                'id': address.id,
                'province': address.province.name,
                'city': address.city.name,
                'district': address.district.name,
                'place': address.place,
                'receiver': address.receiver,
                'mobile': address.mobile
            })

        # 从Redis购物车中查询出被勾选的商品信息
        redis_conn = get_redis_connection('carts')
        # hash
        item_dict = redis_conn.hgetall('carts_%s' % user.id)
        # set中的数据
        cart_selected = redis_conn.smembers('selected_%s' % user.id)
        cart = {}
        # hash中的count和set中的set_id拼接到dict
        for sku_id in cart_selected:
            cart[int(sku_id)] = int(item_dict[sku_id])

        # 查询商品信息
        try:
            skus = SKU.objects.filter(id__in=cart.keys())
        except Exception as e:
            return http.JsonResponse({'code':400,
                                      'errmsg':'获取对应商品失败'})
        sku_list = []
        for sku in skus:
            sku_list.append({
                'id':sku.id,
                'name':sku.name,
                'default_image_url':sku.default_image_url,
                'count':cart[sku.id],
                'price':sku.price
            })

        # 补充运费
        freight = Decimal('10.00')



        # 渲染界面
        context = {
            'addresses': list,
            'skus': sku_list,
            'freight': freight,
        }

        return http.JsonResponse({'code':0,
                                  'errmsg':'ok',
                                  'context':context})

class OrderCommitView(View):
    """订单提交"""

    def post(self, request):
        """保存订单信息和订单商品信息"""
        # 获取当前要保存的订单数据
        json_dict = json.loads(request.body.decode())
        address_id = json_dict.get('address_id')
        pay_method = json_dict.get('pay_method')
        # 校验参数
        if not all([address_id, pay_method]):
            return http.HttpResponseForbidden('缺少必传参数')
        # 判断address_id是否合法
        try:
            address = Address.objects.get(id=address_id)
        except Exception as e:
            return http.HttpResponseForbidden('参数address_id错误')
        # 判断pay_method是否合法
        # OrderInfo.PAY_METHODS_ENUM['xxx'] 代表选择方式
        if pay_method not in [OrderInfo.PAY_METHODS_ENUM['CASH'],
                              OrderInfo.PAY_METHODS_ENUM['ALIPAY']]:
            return http.HttpResponseForbidden('参数pay_method错误')

        # 获取登录用户
        user = request.user
        # 生成订单编号：年月日时分秒+用户编号
        order_id = timezone.localtime().strftime('%Y%m%d%H%M%S')+ ('%09d' % user.id)


        # 显式的开启一个事务
        with transaction.atomic():
            # 创建事务保存点
            save_id = transaction.savepoint()

            # 保存订单基本信息 OrderInfo（一）
            order = OrderInfo.objects.create(
                order_id=order_id,
                user=user,
                address=address,
                total_count=0,
                total_amount=Decimal('0'),
                freight=Decimal('10.00'),
                pay_method=pay_method,
                status=OrderInfo.ORDER_STATUS_ENUM['UNPAID']
                        if pay_method == OrderInfo.PAY_METHODS_ENUM['ALIPAY']
                        else OrderInfo.ORDER_STATUS_ENUM['UNSEND']
            )



            # 从 redis 读取购物车中被勾选的商品信息
            redis_conn = get_redis_connection('carts')
            item_dict = redis_conn.hgetall('carts_%s' % user.id)
            cart_selected = redis_conn.smembers('selected_%s' % user.id)
            carts = {}
            for sku_id in cart_selected:
                carts[int(sku_id)] = int(item_dict[sku_id])
            # 获取选中的商品id:
            sku_ids = carts.keys()

            # 遍历购物车中被勾选的商品信息
            for sku_id in sku_ids:
                # 增加的代码: 增加一个死循环
                while True:
                    # 查询 SKU 信息 sku_id --> sku
                    sku = SKU.objects.get(id=sku_id)

                    # 取出 SKU 数量
                    sku_count = carts[sku.id]
                    # sku_count 销售量 sku.stock 库存
                    if sku_count > sku.stock:
                        # 事务回滚
                        transaction.savepoint_rollback(save_id)
                        return http.JsonResponse({'code': 400,
                                                  'errmsg': '库存不足'})
                    # # SKU减少库存，增加销量
                    # sku.stock -= sku_count
                    # sku.sales += sku_count
                    # sku.save()

                    # 增加的代码: 乐观锁更新库存和销量
                    # 计算差值
                    # 原始库存-销量
                    new_stock = sku.stock - sku_count
                    # 新的库存+销量
                    new_sales = sku.sales + sku_count
                    result = SKU.objects.filter(id=sku_id,
                                                stock=sku.stock).update(stock=new_stock, sales=new_sales)
                    # 如果下单失败，但是库存足够时，
                    # 继续下单，直到下单成功或者库存不足为止
                    if result == 0:
                        continue

                    # 修改SPU销量
                    sku.goods.sales += sku_count
                    sku.goods.save()
                    # 保存订单商品信息 OrderGoods（多）
                    OrderGoods.objects.create(
                        order=order,
                        sku=sku,
                        count=sku_count,
                        price=sku.price,
                    )
                    # 保存商品订单中总价和总数量
                    order.total_count += sku_count
                    order.total_amount += (sku_count * sku.price)

                    # 下单成功或者失败就跳出循环
                    break

                # 添加邮费和保存订单信息
                order.total_amount += order.freight
                order.save()

                # 清除保存点
                transaction.savepoint_commit(save_id)

            # 清除购物车中已结算的商品
            for sku_id in cart_selected:
                pl = redis_conn.pipeline()
                pl.hdel('carts_%s' % user.id, sku_id)
                pl.srem('selected_%s' % user.id, sku_id)
                pl.execute()

        # 响应提交订单结果
        return http.JsonResponse({'code': 0,
                                  'errmsg': '下单成功',
                                  'order_id': order.order_id})

class OrderCommentView(LoginRequiredMixin, View):
    """订单商品评价"""

    def get(self, request):
        """展示商品评价页面"""
        # 接收参数
        order_id = request.GET.get('order_id')
        # 校验参数
        try:
            OrderInfo.objects.get(order_id=order_id,
                                  user=request.user)
        except OrderInfo.DoesNotExist:
            return http.HttpResponseNotFound('订单不存在')

        # 查询订单中未被评价的商品信息
        try:
            uncomment_goods = OrderGoods.objects.filter(order_id=order_id,
                               is_commented=False)
        except Exception:
            return http.HttpResponseServerError('订单商品信息出错')

        # 构造待评价商品数据
        uncomment_goods_list = []
        for goods in uncomment_goods:
            uncomment_goods_list.append({
                'order_id':goods.order.order_id,
                'sku_id':goods.sku.id,
                'name':goods.sku.name,
                'price':str(goods.price),
                'default_image_url':goods.sku.default_image_url,
                'comment':goods.comment,
                'score':goods.score,
                'is_anonymous':str(goods.is_anonymous),
            })

        # 渲染模板
        context = {
            'uncomment_goods_list': uncomment_goods_list
        }
        return render(request, 'goods_judge.html', context)

    def post(self, request):
        """评价订单商品"""
        # 接收参数
        json_dict = json.loads(request.body.decode())
        order_id = json_dict.get('order_id')
        sku_id = json_dict.get('sku_id')
        score = json_dict.get('score')
        comment = json_dict.get('comment')
        is_anonymous = json_dict.get('is_anonymous')
        # 校验参数
        if not all([order_id, sku_id, score, comment]):
            return http.HttpResponseForbidden('缺少必传参数')
        try:
            OrderInfo.objects.filter(order_id=order_id,
                                     user=request.user,
                                     status=OrderInfo.ORDER_STATUS_ENUM['UNCOMMENT'])
        except OrderInfo.DoesNotExist:
            return http.HttpResponseForbidden('参数order_id错误')
        try:
            sku = SKU.objects.get(id=sku_id)
        except SKU.DoesNotExist:
            return http.HttpResponseForbidden('参数sku_id错误')
        if is_anonymous:
            if not isinstance(is_anonymous, bool):
                return http.HttpResponseForbidden('参数is_anonymous错误')

        # 保存订单商品评价数据
        OrderGoods.objects.filter(order_id=order_id,
                                  sku_id=sku_id,
                                  is_commented=False).update(
            comment=comment,
            score=score,
            is_anonymous=is_anonymous,
            is_commented=True
        )

        # 累计评论数据
        sku.comments += 1
        sku.save()
        sku.goods.comments += 1
        sku.goods.save()

        # 如果所有订单商品都已评价，则修改订单状态为已完成
        if OrderGoods.objects.filter(order_id=order_id,
                                     is_commented=False).count() == 0:
            OrderInfo.objects.filter(order_id=order_id).update(status=OrderInfo.ORDER_STATUS_ENUM['FINISHED'])

        return http.JsonResponse({'code': 'OK',
                                  'errmsg': '评价成功'})


class GoodsCommentView(View):
    """订单商品评价信息"""

    def get(self, request, sku_id):
        # 获取被评价的订单商品信息
        order_goods_list = OrderGoods.objects.filter(sku_id=sku_id, is_commented=True).order_by('-create_time')[:30]
        # 序列化
        comment_list = []
        for order_goods in order_goods_list:
            username = order_goods.order.user.username
            comment_list.append({
                'username': username[0] + '***' + username[-1] if order_goods.is_anonymous else username,
                'comment':order_goods.comment,
                'score':order_goods.score,
            })
        return http.JsonResponse({'code':'OK', 'errmsg':'OK', 'comment_list': comment_list})